package com.example.yrdev.ordering_system.User_Login_Register;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Common.Setting;
import com.example.yrdev.ordering_system.Database.DingHanDB;
import com.example.yrdev.ordering_system.Model.CardTypeInfo;
import com.example.yrdev.ordering_system.Model.FixPriceTimeSchedule;
import com.example.yrdev.ordering_system.Model.Good;
import com.example.yrdev.ordering_system.Model.GoodType;
import com.example.yrdev.ordering_system.Model.Operator;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.SettingActivity;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.homeOptions.MainActivity;
import com.example.yrdev.ordering_system.http.HttpClient;
import com.example.yrdev.ordering_system.http.HttpResponseHandler;
import com.example.yrdev.ordering_system.http.NetWorkConstant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

import com.dhF9.dhF9Jni;

/**
 * Created by yrdev on 7/18/16.
 */

public class LoginActivity extends CommonActivity {

    public EditText currentEditText;
    ArrayList<GoodType> goodTypeArrayList;
    ArrayList<Good> goodDetailArrayList;
    ArrayList<Operator> operatorArrayList;
    private boolean firstLogin;

    @InjectView(R.id.user_name)EditText userName;
    @InjectView(R.id.user_pass)EditText userPass;

   @InjectView(R.id.login)Button loginBut;
    @InjectView(R.id.devNo)TextView devNo;
    @InjectView(R.id.devNum)TextView devNum;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_page_layout);
        GlobalFunction.context=this;


        getSupportActionBar().hide();
        initView();
       // initNFCParam();

        NetWorkConstant.initNetwork(this);//初始化网络信息

    }

    private boolean hasLogin(){//检查是否登录过

        boolean stat=true;

        SharedPreferences preferences=getSharedPreferences("User",Context.MODE_PRIVATE);
        int marker=preferences.getInt("loginMark",0);


        if (marker==1)
            stat=false;



        return stat;
    }



    void hideViewKeyboard(){
        hideKeyBoard();
        if (currentEditText!=null){
            currentEditText.setCursorVisible(false);
        }
    }

    @Override
    public void initView() {
        super.initView();

        ButterKnife.inject(this);
        Setting.getInstance().init();

        devNo.setText(Setting.getInstance().getDevID());
        devNum.setText(Setting.getInstance().getDeviceID());


        goodTypeArrayList=GoodType.getTypeList(this);
        goodDetailArrayList=Good.getItemDetailList(this);

        loginBut.setOnClickListener(loginListener());

        LinearLayout login_background=(LinearLayout)findViewById(R.id.login_background);
        login_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               hideViewKeyboard();
            }
        });




        userName.setOnTouchListener(editTextOnTouchListener());
        userPass.setOnTouchListener(editTextOnTouchListener());

        userName.setOnEditorActionListener(editorActionListener());
        userPass.setOnEditorActionListener(editorActionListener());

    }



    private  boolean startLogin(){
        boolean stat=false;

        if (userName.getText().toString().length()==0){
            GlobalFunction.ToastAlert(this,"请输入操作员ID");
            return stat;

        }

        if (userPass.getText().toString().length()==0) {

            GlobalFunction.ToastAlert(this,"请输入操作员密码");

            return stat;
        }


        if (userPass.getText().toString().length()>0&& userName.getText().toString().length()>0){
            stat=true;

        }


            return stat;

    }

    View.OnClickListener loginListener(){
        View.OnClickListener login=new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                firstLogin=hasLogin();

/*
                if (firstLogin) {//第一次登录

                    if (startLogin()){

                        GlobalFunction.showProgress(LoginActivity.this,"提示","正在登录");

                      //  getSystemSetting();

                        //getOperatorinfo();

                    }

                }else {*/


                    if (startLogin()){

                        GlobalFunction.showProgress(LoginActivity.this,"提示","正在登录");

                        firstLogin=true;

                        prepareLogin();

                    }

              //  }




            }
        };
        return login;

    }

    private void prepareLogin(){

       // assignData();

        if (validUserPass())//登录用户成功
        {

            checkLoginSuccess();

        }else {


            GlobalFunction.ToastAlert(this,"账户密码有误");
            GlobalFunction.dismissProgress();
        }


    }


    private  void  getFixPriceTime(){//定额时间段
        HashMap<String,Object> hashMap=new HashMap<>();

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getFixPriceTime,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");
                    GlobalFunction.printTextByTag(response);
                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);

                    JSONArray jsonArray = respItem.getJSONArray("item");

                    for (int i = 0; i < jsonArray.length(); i++) {

                        JSONObject object = jsonArray.getJSONObject(i);

                        FixPriceTimeSchedule fixPriceTimeSchedule=new FixPriceTimeSchedule();
                        fixPriceTimeSchedule.cardID=object.getString("id");

                        fixPriceTimeSchedule.timePriceSchedule.put(object.getString("time01"),"breakfast");
                        fixPriceTimeSchedule.timePriceSchedule.put(object.getString("time02"),"lunch");
                        fixPriceTimeSchedule.timePriceSchedule.put(object.getString("time03"),"dinner");
                        fixPriceTimeSchedule.timePriceSchedule.put(object.getString("time04"),"midnight");
                       // fixPriceTimeSchedule.timePriceSchedule.put(object.getString("time05"),"");


                        FixPriceTimeSchedule.getInstance().fixPriceTimeScheduleArrayList.add(fixPriceTimeSchedule);

                    }

                  // getFixPrice();




                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(LoginActivity.this, "Login Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(LoginActivity.this, "无法访问服务器");
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        devNo.setText(Setting.getInstance().getDevID());


    }

/*
    private  void  getSystemSetting(){
        HashMap<String,Object> hashMap=new HashMap<>();

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getSystemSetting,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);

                     Setting.getInstance().parseJSON(respItem,LoginActivity.this);

                //    getFixPriceTime();

                //    getOperatorinfo();

               //    getAllowCardType();



                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(LoginActivity.this, "Login Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(LoginActivity.this, "无法访问服务器");
            }
        });
    }
*/
private  void  getSystemSetting(){
    final HashMap<String,Object> hashMap=new HashMap<>();

    HttpClient.postWithFunction(NetWorkConstant.HTTP_getSystemSetting,hashMap,new HttpResponseHandler(){
        @Override
        protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

            super.handleSuccessMessage(statusCode, headers, responseBody);
            JSONObject jsonObject;


            try {
                jsonObject = new JSONObject(responseBody);
                String response = jsonObject.getString("response");

                GlobalFunction.printTextByTag(response);

                JSONObject respBody = new JSONObject(response);
                String body = respBody.getString("body");

                JSONObject respItem = new JSONObject(body);


                JSONArray jsonArray = respItem.getJSONArray("item");



                    JSONObject temp=  jsonArray.getJSONObject(0);
                    Setting.getInstance().parseJSON(temp,LoginActivity.this);





            } catch (Exception e) {

                GlobalFunction.printTextByTag(e.getMessage());
                GlobalFunction.dismissProgress();
              //  GlobalFunction.ToastAlert(context, "download setting fail");
                GlobalFunction.ToastAlert(LoginActivity.this, "Login Fail");
            }

        }

        @Override
        protected void handleFailureMessage(Request request, IOException e) {
            super.handleFailureMessage(request, e);
            GlobalFunction.dismissProgress();
        //    GlobalFunction.ToastAlert(context, "无法访问服务器");
            GlobalFunction.ToastAlert(LoginActivity.this, "无法访问服务器");


        }
    });
}
    private  void  getAllowCardType(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("cardType","");

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getAllowCardType,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);


                    JSONArray jsonArray = respItem.getJSONArray("item");


                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject temp=  jsonArray.getJSONObject(i);
                        //Setting.getInstance().parseAllowCardType(temp);
                        CardTypeInfo.getInstance().addCardTypeList(temp);

                    }


//                    JSONObject respBody = new JSONObject(response);
//                    String body = respBody.getString("body");
//
//                    JSONObject respItem = new JSONObject(body);
//
//                    Setting.getInstance().parseJSON(respItem,LoginActivity.this);
//
//                    getFixPriceTime();
//
//                    getOperatorinfo();



                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(LoginActivity.this, "Login Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(LoginActivity.this, "无法访问服务器");
            }
        });
    }


    private  boolean existOperator(Operator operator){

        boolean stat=false;

        operatorArrayList=Operator.getOperatorList(this);

        for (Operator op:operatorArrayList){

            if (op.getOperCardNo().equals(operator.getOperCardNo()) ) {

                stat = true;

                break;
            }
        }


        return stat;

    }
    private  void getOperatorinfo(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("operID","");

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getOperatorInfo,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);


                    JSONArray jsonArray = respItem.getJSONArray("item");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Operator operator = new Operator(object);

                     //   if (!existOperator(operator)) {

                            Operator.saveOperator(LoginActivity.this, operator);


                       // }

                        // GoodType.storeToDB(LoginActivity.this,goodType);
                        //   typeAdapter.addJsonObject(object);

                    }


                    if (validUserPass()) {

//                        if (goodTypeArrayList.size() == 0) {//没获取过商品类型列表
//
//                            getItemTypeList();
//                            return;
//
//                        }
//
//                        if (goodDetailArrayList.size() == 0) {//没获取过商品类型列表
//
//                            getItemDetailList();
//                            return;
//
//                        }

                        checkLoginSuccess();

                    } else {

                        GlobalFunction.dismissProgress();
                        GlobalFunction.ToastAlert(LoginActivity.this, "抱歉,操作员ID/密码不正确");

                    }


                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(LoginActivity.this, "Login Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(LoginActivity.this, "无法访问服务器");
            }
        });
    }


    public boolean validUserPass(){
     boolean stat=false;
    operatorArrayList= DingHanDB.getInstance(this).getOperatorList();

        for (Operator op:operatorArrayList){

            GlobalFunction.printTextByTag("op:"+op.getEmployeeID()+":"+op.getPassword());

            if (op.getEmployeeID().equals(userName.getText().toString())&&
                    op.getPassword().equals(userPass.getText().toString())){
               stat=true;

            }

        }

        return stat;


    }
    private  void checkLoginSuccess(){
        if (goodTypeArrayList.size()==0){//刷新数组
            goodTypeArrayList=GoodType.getTypeList(this);
        }

        if (goodDetailArrayList.size()==0){//刷新数组
            goodDetailArrayList=Good.getItemDetailList(this);

        }

     //   if (firstLogin)
      //      handleFirstLogin();
      //  else
            initData();

       // if (goodTypeArrayList.size()>0&& goodDetailArrayList.size()>0){

            assignCurrentOperatorInfo();

          //  Setting.getInstance().init(this);

              GlobalFunction.ToastAlert(LoginActivity.this,"登录成功");
              GlobalFunction.dismissProgress();
              gotoActivity(MainActivity.class,0);
            // gotoActivity(HomeActivity.class,0);

      //  }

    }

    private void initData(){
      //  FixPriceTimeSchedule.getInstance().init();
        Setting.getInstance().init();


    }

    private void handleFirstLogin(){
        SharedPreferences preferences=getSharedPreferences("User",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();


        editor.putInt("loginMark",1).apply();
        GlobalFunction.printTextByTag("handle");
//        GlobalFunction.printTextByTag(Setting.getInstance().getSecurity());

        try {

          //  Setting.getInstance().saveSetting();
          //  FixPriceTimeSchedule.getInstance().saveSchedule();


        }catch (Exception e){

            GlobalFunction.printTextByTag("save error");

        }



    }

    private void assignCurrentOperatorInfo(){

        try {


            for (Operator op:operatorArrayList){

                if (op.getEmployeeID().equals(userName.getText().toString())){

                    Operator.setInstance(op);

                    break;
                }
            }

            GlobalFunction.printTextByTag(Operator.getIntance().returnCommodityAuthority()+"");

        }catch (Exception e){

            e.printStackTrace();

        }


    }
//    private void getItemTypeList(){//获取商品类型
//        HashMap<String,Object> body=new HashMap<>();
//        body.put("updateTime","");
//        body.put("barcode","");
//        body.put("commodityID","");
//
//
//
//        HttpClient.postWithFunction(NetWorkConstant.HTTP_getComTypeInfo,body,new HttpResponseHandler(){
//
//            @Override
//            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
//                super.handleSuccessMessage(statusCode, headers, responseBody);
//
//
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(responseBody);
//                    String response= jsonObject.getString("response");
//
//                    JSONObject respBody=new JSONObject(response);
//                    String body=respBody.getString("body");
//
//                    JSONObject respItem=new JSONObject(body);
//
//
//                    JSONArray jsonArray=respItem.getJSONArray("item");
//
//                    for (int i = 0; i <jsonArray.length() ; i++) {
//                        JSONObject object=jsonArray.getJSONObject(i);
//                        GoodType goodType=new GoodType(object.getString("id"),object.getString("name"));
//                        GoodType.storeToDB(LoginActivity.this,goodType);
//                     //   typeAdapter.addJsonObject(object);
//
//                    }
//
//                    getItemDetailList();
//
//                   // typeAdapter.notifyDataSetChanged();
//
//                   // getItemDetail(typeAdapter.getGoodTypeArrayList().get(0).getId());
//                    //  selectView(1);//默认第一个选中
//
//                }catch (Exception e){
//
//
//                    GlobalFunction.ToastAlert(LoginActivity.this,"data is empty");
//
//                }
//
//
//            }
//
//            @Override
//            protected void handleFailureMessage(Request request, IOException e) {
//                super.handleFailureMessage(request, e);
//
//
//
//            }
//
//        });
//
//
//    }

    private void getItemDetailList(){
        if (goodTypeArrayList.size()==0){//刷新数组
            goodTypeArrayList=GoodType.getTypeList(this);
        }




        HttpClient.postWithFunction(NetWorkConstant.HTTP_getComDetailBaseOnType,null,new HttpResponseHandler(){

            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);


                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseBody);
                    String response= jsonObject.getString("response");
                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody=new JSONObject(response);
                    String body=respBody.getString("body");

                    JSONObject respItem=new JSONObject(body);


                    JSONArray jsonArray=respItem.getJSONArray("item");


                    for (int i = 0; i <jsonArray.length() ; i++) {
                        JSONObject object=jsonArray.getJSONObject(i);
                        Good good=new Good(object);

                        Good.storeToDB(LoginActivity.this,good);




                        //goodAdapter.addJsonObject(object);

                    }


                    checkLoginSuccess();

                    //GlobalFunction.printTextByTag("size"+Good.getItemDetailList(LoginActivity.this).size());






//                    itemDetailList.setAdapter(new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,goodArrayList));

                }catch (Exception e){
                    GlobalFunction.ToastAlert(LoginActivity.this,"data is empty");
                    GlobalFunction.printTextByTag(e.getMessage());

                }


            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);


            }

        });

    }

    TextView.OnEditorActionListener editorActionListener(){
        TextView.OnEditorActionListener editorActionListener=new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        hideViewKeyboard();

                return false;
            }
        };
        return editorActionListener;

    }
    View.OnTouchListener editTextOnTouchListener(){
        View.OnTouchListener touchListener=new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                EditText editText=(EditText)view;
                editText.setCursorVisible(true);
                currentEditText=editText;

                return false;

            }
        };
                return touchListener;
    }
    View.OnFocusChangeListener ediTextFocusListener(){
        View.OnFocusChangeListener focusChangeListener=new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);

                if (imm.isAcceptingText()) {
                    GlobalFunction.printText("tag","c");
                } else {
                    GlobalFunction.printText("tag","d");
                }
//                EditText editText=(EditText)view;
//                editText.setCursorVisible(true);
            }
        };
                return focusChangeListener;

    }

    //for reading MI CARD
    @Override
    protected void onResume() {
        super.onResume();

        try {
            reader.processIntent(mNfcAdapter,getIntent());
        }catch (Exception e){

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {

            reader.processIntent(mNfcAdapter, intent);
        }catch (Exception e){

            e.printStackTrace();
        }


    }

    public   void goToSetting(View view){

      gotoActivity(SettingActivity.class,0);

    }

}
